package com.cloudcc.mobile.bull.http;

import android.app.Dialog;
import android.content.Context;
import android.util.Log;

import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;

import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;


/**
 * Created by dev08 on 2017/7/19.
 */

public class XutilsHttp {
    Context mContext;

    public Boolean isShowLoadding = true;
        public Dialog dialog;
    private static String TAG = "xutils";
    private static final int TIME_OUT = 10 * 1000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码

    public boolean isLoginDia = true;

    public XutilsHttp(Context context) {
        mContext = context;
        //TAG = ((BaseActivity) mContext).getActivityNamne();
//        dialog = ProgressDialogUtils.createLoadingDialog(context, "加载中,请稍后...");
    }


    /**
     * 图片上传
     *
     * @param serviceName
     * @param data
     * @param file
     * @param call
     */

    public void postImg(final String serviceName, final String data, final String file, final CommonCallback call) {
        String host = StringUtils.replace(UrlManager.getInterfaceUrl(),
                "https://", "http://");

        final String url = host + "?serviceName=uploadImg&data=" + data
                + "&binding=" + RunTimeManager.getInstance().getServerBinding();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s = uploadFile(new File(file), url);
                    if (s != null) {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject obj = jsonObject.getJSONObject("data");
                        call.result(obj);
                        // imgId = obj.getString("imgId");

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dialog.dismiss();
                }
            }
        }).start();

    }


    /**
     * 上传图片
     *
     * @param file
     * @param RequestURL
     * @return
     */

    public static String uploadFile(File file, String RequestURL) {
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if (file != null) {
                /**
                          * 当文件不为空，把文件包装并且上传
                          */
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                          * 这里重点注意： name里面的值为服务端需要key 只有这个key 才可以得到对应的文件
                          * filename是文件的名字，包含后缀名的 比如:abc.png
                          */
                sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
                        + file.getName() + "\"" + LINE_END);

                sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                          * 获取响应码 200=成功 当响应成功，获取响应的流
                          */
                int res = conn.getResponseCode();
                Log.e(TAG, "response code:" + res);
                // if(res==200)
                // {
                Log.e(TAG, "request success");
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
                Log.e("---"+TAG, "result : " + result);
                // }
                // else{
                // Log.e(TAG, "request error");
                // }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

public interface CommonCallback {
    public void result(JSONObject res);

    public void error();
}
}
